from datetime import datetime, date
import logging
from logging.handlers import RotatingFileHandler
from config import config
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import flask_excel as excel
from flask.json.provider import DefaultJSONProvider
from flask_simple_captcha import CAPTCHA
from flask_jwt_extended import JWTManager

CAPTCHA_CONFIG = {
    'SECRET_CAPTCHA_KEY': '5984d2c2-2721-4f51-85bf-dfcc7aedd03',
    'CAPTCHA_LENGTH': 4,
    'CAPTCHA_DIGITS': True,
    'EXPIRE_SECONDS': 600,
}

def setup_logger(name):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    # Create a rotating file handler
    file_handler = RotatingFileHandler('myapp.log', encoding='utf-8', maxBytes=10*1024*1024, backupCount=5)
    file_handler.setLevel(logging.INFO)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    # Create a formatter and set it for the handler
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s - %(message)s')
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)

    # Add the handler to the logger if it hasn't been added yet
    if not logger.hasHandlers():
        logger.addHandler(file_handler)
        logger.addHandler(console_handler)

    return logger

class CustomJSONEncoder(DefaultJSONProvider):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return super().default(obj)

db = SQLAlchemy()
captcha = CAPTCHA(config=CAPTCHA_CONFIG)
jwt = JWTManager()

def create_app(config_name):
    app = Flask(__name__)
    #  替换默认的json编码器
    app.json_encoder = CustomJSONEncoder
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    app.secret_key = 's3cr3tCC'
    db.init_app(app)
    jwt.init_app(app)
    captcha.init_app(app)

    #注册模块路由
    from myapp.routes import system as system_bp
    app.register_blueprint(system_bp)
    print(system_bp.route)

    excel.init_excel(app)
    return app

